<template>
  <div>
    <h3 class="title">单文件BASE64上传</h3>
    <div class="border_dot">
      <form id="formbs">
        <input
          ref="fileRef"
          type="file"
          style="display: none"
          accept=".png,.jpg,.jpeg,.zip"
        />
      </form>
      <button class="btn select_btn" @click="handleFile">选择文件</button>
      <button class="btn update_btn" @click="handleUpdate">上传</button>
      <div>请上传PNG/JPG/ZIP类型图片</div>
      <div class="file_item_wrap" v-if="file">
        <span class="file_name">{{ file.name }}</span>
        <span class="file_remove" @click="handleRemove">移除</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { readAsDataURL } from "@/utils/index";
import { updateFileBase } from "@/api/update";

const fileRef = ref<null | HTMLInputElement>(null);
const file = ref<null | File>(null);

async function handleUpdate() {
  if (!file.value) {
    alert("请选择文件");
    return;
  }
  const base64 = await readAsDataURL<string>(file.value);
  const selectBtn = document.querySelector(".select_btn");
  const updateBtn = document.querySelector(".update_btn");
  selectBtn?.setAttribute("disabled", "disabled");
  updateBtn?.setAttribute("loading", "loading");
  try {
    const res = await updateFileBase<
      { file: string; filename: string },
      { type: number; path: string }
    >(
      {
        file: encodeURIComponent(base64),
        filename: file.value.name,
      },
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        onUploadProgress: (ev: Event) => {
          console.log(ev, "update");
        },
      }
    );
    res.type === 0 ? alert("文件已存在") : alert("上传成功");
    file.value = null;
    (document.querySelector("#formbs") as HTMLFormElement).reset();
  } finally {
    selectBtn?.removeAttribute("disabled");
    updateBtn?.removeAttribute("loading");
  }
}
function handleFile() {
  fileRef.value?.click();
}
function handleRemove() {
  file.value = null;
}
onMounted(() => {
  fileRef.value?.addEventListener("change", (ev: Event) => {
    file.value = (ev.target as HTMLInputElement).files![0];
  });
});
</script>

<style></style>
